import Https from "@/utils/Https";
import {
  ActionType,
  PageContainer,
  ProDescriptions,
  ProTable,
} from "@ant-design/pro-components";
import React, { useState, useRef, FC } from "react";
import { connect } from "umi";
import { Badge, Checkbox, Drawer } from "antd";
import styles from "./index.less";
const NewsList: FC<any> = (props) => {
  const { dispatch, messageCount } = props;
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  const [status, setStatus] = useState(false);
  const [open, setOpen] = useState(false);
  const [itemList, setItemList] = useState([]);
  const [messageItem, setMessageItem] = useState({});
  const [key, setKey] = useState("0");
  //已读消息
  const readMessage = async (id) => {
    let res = await Https.post(`/message/center/read/${id}`, {}, true);
    if (res.code == 200) {
      actionRef.current && actionRef.current.reload();
      let newCount = messageCount > 0 ? messageCount - 1 : 0;
      dispatch({
        type: "global/queryMessage",
        params: {
          count: newCount,
        },
      });
    }
  };
  //所有已读
  const readAll = async () => {
    let res = await Https.post("/message/center/allRead", {}, true);
    if (res.code == 200) {
      actionRef.current && actionRef.current.reload();
      dispatch({
        type: "global/queryMessage",
        params: {
          count: 0,
        },
      });
    }
  };
  const columns = [
    {
      title: "状态",
      dataIndex: "messageStatus",
      hideInSearch: true,
      valueEnum: {
        0: { text: "未读", status: "error" },
        1: { text: "已读", status: "success" },
      },
    },
    {
      title: "消息标题",
      dataIndex: "messageTitle",
      ellipsis: true,
      render: (_, record) => (
        <a
          onClick={() => {
            setOpen(true);
            setMessageItem(record);
            if (record.messageStatus == 0) {
              readMessage(record.id);
            }
          }}
        >
          {record.messageTitle}
        </a>
      ),
    },
    {
      title: "消息内容",
      dataIndex: "messageContent",
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: "发送时间",
      dataIndex: "remindTime",
      hideInSearch: true,
      render: (_, record) => (record.remindTime ? record.remindTime : ""),
    },
  ];
  const columnsTwo = [
    {
      title: "状态",
      dataIndex: "messageStatus",
      hideInSearch: true,
      valueEnum: {
        0: { text: "未读", status: "error" },
        1: { text: "已读", status: "success" },
      },
    },
    {
      title: "消息标题",
      dataIndex: "messageTitle",
      ellipsis: true,
      render: (_, record) => (
        <a
          onClick={() => {
            setOpen(true);
            setMessageItem(record);
            if (record.messageStatus == 0) {
              readMessage(record.id);
            }
          }}
        >
          {record.messageTitle}
        </a>
      ),
    },
    {
      title: "消息类型",
      dataIndex: "messageCategory",
      hideInSearch: true,
      valueEnum: {
        1: { text: "平台消息" },
        2: { text: "服务消息" },
        3: { text: "交易消息" },
      },
    },
    {
      title: "消息内容",
      dataIndex: "messageContent",
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: "发送时间",
      dataIndex: "remindTime",
      hideInSearch: true,
      render: (_, record) => (record.remindTime ? record.remindTime : ""),
    },
  ];
  //获取消息中心列表
  const getList = async (p) => {
    setLoading(true);
    let records = [];
    let total = 0;
    let objData = {
      ...p,
      messageCategory: key == "0" ? "" : key,
      messageStatus: status ? 0 : 1,
    };
    if (!status) {
      delete objData.messageStatus;
    }
    let res = await Https.get("/message/center/messageList", objData, true);
    setLoading(false);
    if (res.code == 200) {
      records = res.data.records;
      total = res.data.total;
    }
    return {
      success: true,
      data: records,
      total: total,
    };
  };
  //获取不同类型未读消息数量
  const getReadMessage = async () => {
    const messageTypeList = [
      { key: 1, name: "平台消息" },
      { key: 2, name: "服务消息" },
      { key: 3, name: "交易消息" },
    ];
    let res = await Https.get(
      "/message/center/queryUserMessageCount",
      {},
      true
    );
    let objList = [];
    if (res.code == 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        messageTypeList.map((item) => {
          let count = 0;
          let hasCount = res.data.records.filter(function (o) {
            return o.messageCategory == item.key;
          });
          count = hasCount.length > 0 ? hasCount[0].count : 0;
          objList.push({
            key: item.key,
            tab: (
              <Badge size="small" count={count > 99 ? "99+" : count}>
                {item.name}
              </Badge>
            ),
          });
        });
        setItemList(objList);
      } else {
        messageTypeList.map((item) => {
          objList.push({
            key: item.key,
            tab: `${item.name}(0)`,
          });
        });
        setItemList(objList);
      }
    }
  };
  return (
    <div key="NewsList" className={styles.NewsList}>
      <PageContainer
        title="消息通知"
        tabList={[
          { key: 0, tab: "全部消息" },
          { key: 1, tab: "平台消息" },
          { key: 2, tab: "服务消息" },
          { key: 3, tab: "交易消息" },
        ]}
        tabActiveKey={key}
        onTabChange={(e) => {
          actionRef.current && actionRef.current.reset();
          actionRef.current && actionRef.current.reload();
          setStatus(false);
          setKey(e);
        }}
      >
        <ProTable
          columns={key == "0" ? columnsTwo : columns}
          rowKey="id"
          actionRef={actionRef}
          loading={loading}
          toolBarRender={() => [
            <>
              <Checkbox
                checked={status}
                onChange={(e) => {
                  setStatus(e.target.checked);
                  actionRef.current && actionRef.current.reset();
                }}
              >
                只看未读
              </Checkbox>
              <a
                onClick={() => {
                  readAll();
                }}
              >
                全部转为已读
              </a>
            </>,
          ]}
          pagination={{
            showSizeChanger: true,
          }}
          request={async (params) => {
            return await getList(params);
          }}
        />
      </PageContainer>
      <Drawer
        open={open}
        title="消息详情"
        forceRender
        width="40%"
        onClose={() => setOpen(false)}
      >
        <ProDescriptions title={messageItem.messageTitle} column={2}>
          <ProDescriptions.Item valueType="text" label="发布者">
            -
          </ProDescriptions.Item>
          <ProDescriptions.Item valueType="text" label="发布时间">
            {messageItem.remindTime || "-"}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="" valueType="text">
            <div
              style={{
                background: "#9696961a",
                borderRadius: "3px",
                padding: "16px",
                width: "100%",
              }}
            >
              {messageItem.messageContent || "-"}
            </div>
          </ProDescriptions.Item>
        </ProDescriptions>
      </Drawer>
    </div>
  );
};
export default connect(({ global }) => ({
  ...global,
}))(NewsList);
